#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMessageBox>
#include <QFileDialog>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

bool MainWindow::on_actionSave_as_triggered()
{
    QString fileName = QFileDialog::getSaveFileName(
                this,
                "Imagenes Medicas - Save as",
                "/Users/AlejoMac/Documents",
                "Imagenes medicas (*.dcm)::All Files (*.*)");
    if(!fileName.isEmpty()){
        curFile=fileName;
        return saveFile();
    }
    return false;
}

bool MainWindow::saveFile()
{
    QFile file(curFile);
    if(file.open(QFile::WriteOnly)){
        file.write(ui->plainTextEdit->toPlainText().toUtf8());
        return true;
    }else{
        QMessageBox::warning(
                    this,
                    "Imagenes Medicas",
                    tr("No se puede escribir archivo %1.Error\Error: %2")
                    .arg(curFile)
                    .arg(file.errorString()));
        return false;
    }
}

bool MainWindow::maybeSave()
{
    if(ui->plainTextEdit->document()->isModified()){
        QMessageBox::StandardButton ret=
                QMessageBox::warning(
                    this,
                    "Imagenes Medicas",
                    tr("El documento ha sido modificado"
                    "¿Quiere grabar sus cambios?"),
                    QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
        if (ret==QMessageBox::Yes){
            return on_action_Save_triggered();
        }else if(ret==QMessageBox::Cancel)
            return false;
    }
    return true;
}

bool MainWindow::on_action_Save_triggered()
{
    if (curFile.isEmpty())
          return on_actionSave_as_triggered();
    else
        return saveFile();
}

bool MainWindow::on_action_Open_File_triggered()
{
    if(maybeSave()){
        QString fileName=QFileDialog::getOpenFileName(
                    this,
                    "TextEditor - Open file",
                    "/Users/AlejoMac/Documents",
                    "Imagenes medicas (*.txt)::All Files (*.*)");
        if (!fileName.isEmpty()){
            QFile file(fileName);
            if (file.open(QFile::ReadOnly)){
                ui->plainTextEdit->setPlainText(file.readAll());
            }else{
                QMessageBox::warning(
                            this,
                            "Imagenes Medicas",
                            tr("No se puede leer archivo %1. \nError: %2")//Traducible
                            .arg(fileName)
                            .arg(file.errorString()));
            }
        }

    }
}
